package com.bnz.servlet;

import com.alibaba.fastjson.JSON;
import com.bnz.pojo.Classes;
import com.bnz.pojo.R;
import com.bnz.service.ClassesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/classes")
public class ClassesServlet extends HttpServlet {

    private ClassesService classesService;
    @Override
    public void init() throws ServletException {
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
         classesService = wac.getBean(ClassesService.class);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String cmd = req.getParameter("cmd");
        if (StringUtils.isNotBlank(cmd)) {
            if ("list".equals(cmd)) {
                list(req,resp);
            }
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        List<Classes> classesList = classesService.findAll();
        R classes = R.ok().data("list", classesList);
        resp.getWriter().println(JSON.toJSONString(classes));
        resp.getWriter().flush();
    }
}
